#!/bin/bash

# =================================================================
# FEATURES:
# 1. One-click to start development server
# 2. Multiple browser opening methods (for maximum compatibility)  
# 3. Compatible with all Node.js versions
# 4. Multiple fallbacks if one method fails
# =================================================================

echo "===================================="
echo "    Hello Frontend Startup Tool"
echo "===================================="
echo

# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

# Check dependencies
if [ ! -d "node_modules" ]; then
    echo "[INFO] Dependencies not installed. Installing now..."
    npm install --registry=https://registry.npmmirror.com --legacy-peer-deps
    if [ $? -ne 0 ]; then
        echo "[ERROR] Failed to install dependencies."
        echo "Press any key to exit..."
        read -n 1 -s
        exit 1
    fi
    echo "[SUCCESS] Dependencies installed."
    echo
fi

echo "[INFO] Starting development server..."
echo "[INFO] Browser will open automatically after server is ready..."
echo "[INFO] Press Ctrl+C to stop the server when done"
echo

# 设置环境变量并运行vue-cli-service (Mac兼容方式)
export NODE_OPTIONS=--openssl-legacy-provider

# 设置中断处理，确保清理工作能够执行
trap cleanup INT

cleanup() {
    echo
    echo "[INFO] Stopping server..."
    echo "[INFO] Server has been stopped."
    echo "Press any key to exit..."
    read -n 1 -s
    exit 0
}

# 启动开发服务器并监控输出
./node_modules/.bin/vue-cli-service serve &
SERVER_PID=$!

# 等待服务器启动完成
echo "[INFO] Waiting for server to start..."
while ! curl -s http://localhost:1024 > /dev/null 2>&1; do
    sleep 1
    # 检查服务器进程是否仍在运行
    if ! kill -0 $SERVER_PID 2>/dev/null; then
        echo "[ERROR] Server failed to start"
        exit 1
    fi
done

echo "[INFO] Server is ready! Opening browser..."
echo "[INFO] If browser doesn't open automatically, visit: http://localhost:1024/"

# 打开浏览器
open "http://localhost:1024/"

# 等待服务器进程结束
wait $SERVER_PID

# Check if the process ended with an error
if [ $? -ne 0 ]; then
    echo
    echo "[ERROR] Server stopped unexpectedly with error code $?"
    echo "[INFO] Please check the error messages above."
fi

# Clean up
if [ -f "redirect.html" ]; then
    rm redirect.html
fi

echo
echo "[INFO] Server has been stopped."
echo "Press any key to exit..."
read -n 1 -s